﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;

namespace TDUpdate
{
    public class UpdateComponentCollection : Collection<UpdateComponent>
    {
        public event EventHandler<UpdateComponentCollectionChangedEventArgs> Changed;

        protected override void InsertItem(int index, UpdateComponent newItem)
        {
            base.InsertItem(index, newItem);

            EventHandler<UpdateComponentCollectionChangedEventArgs> temp = Changed;
            if (temp != null)
            {
                temp(this, new UpdateComponentCollectionChangedEventArgs(ChangeType.Added, newItem));
            }
        }

        protected override void SetItem(int index, UpdateComponent newItem)
        {
            UpdateComponent replaced = Items[index];
            base.SetItem(index, newItem);

            EventHandler<UpdateComponentCollectionChangedEventArgs> temp = Changed;
            if (temp != null)
            {
                temp(this, new UpdateComponentCollectionChangedEventArgs(ChangeType.Added, newItem));
                temp(this, new UpdateComponentCollectionChangedEventArgs(ChangeType.Removed, replaced));
            }
        }

        protected override void RemoveItem(int index)
        {
            UpdateComponent removedItem = Items[index];
            base.RemoveItem(index);

            EventHandler<UpdateComponentCollectionChangedEventArgs> temp = Changed;
            if (temp != null)
            {
                temp(this, new UpdateComponentCollectionChangedEventArgs(ChangeType.Removed, removedItem));
            }
        }

        protected override void ClearItems()
        {
            base.ClearItems();

            EventHandler<UpdateComponentCollectionChangedEventArgs> temp = Changed;
            if (temp != null)
            {
                temp(this, new UpdateComponentCollectionChangedEventArgs(ChangeType.Cleared, null));
            }
        }
    }

    // Event argument for the Changed event.
    //
    public class UpdateComponentCollectionChangedEventArgs : EventArgs
    {
        public readonly UpdateComponent ChangedItem;
        public readonly ChangeType ChangeType;

        public UpdateComponentCollectionChangedEventArgs(ChangeType type, UpdateComponent component)
        {
            ChangedItem = component;
            ChangeType = type;
        }
    }

    public enum ChangeType
    {
        Added,
        Removed,
        Cleared
    }
}
